package com.autosalon.ui.automobil.action;

import com.autosalon.DAO.DaoFactory;
import com.autosalon.model.Doplnek;
import com.autosalon.ui.automobil.Automobil;
import com.autosalon.ui.automobil.state.AutomobilStateHolder;
import com.vaadin.ui.Button.ClickEvent;

/**
 *  Trida slouzici k editaci autmobilu. Nacteni puvodnich hodnot.
 * @author Petr Kriegisch
 */
public class EditAutomobilAction extends AbstractAutomobilAction {

    com.autosalon.model.Automobil vybranyAutomobil;
    Doplnek doplnek;

    public EditAutomobilAction(Automobil automobil) {
        super(automobil);
    }

    @Override
    public void buttonClick(ClickEvent event) {
        vybranyAutomobil = (com.autosalon.model.Automobil) DaoFactory.getinstance().getAutomobil().getById(Long.parseLong(event.getButton().getData().toString()));
        automobil.getLblKm().setValue(vybranyAutomobil.getNajeto());
        automobil.getLblKm().setEnabled(false);
        automobil.getPdDatum().setValue(vybranyAutomobil.getDatumVyroby());
        automobil.getPdDatum().setEnabled(false);
        automobil.getCbVyrobce().setValue(vybranyAutomobil.getModel().getVyrobce().getNazev_vyrobce());
        automobil.getCbVyrobce().setEnabled(false);
        automobil.getCbModel().setValue(vybranyAutomobil.getModel().getNazev_modelu());
        automobil.getCbModel().setEnabled(false);
        automobil.getBtnUpdate().setData(vybranyAutomobil.getId());
        automobil.getLblCena().setValue(vybranyAutomobil.getCena());
        automobil.getTsVybava().removeAllItems();

        for (Object object : DaoFactory.getinstance().getDoplnek().getAll(0, Integer.MAX_VALUE)) {
            doplnek = (Doplnek) object;
            automobil.getTsVybava().addItem(doplnek.getPopis_doplnku());
            for (Doplnek doplnek2 : vybranyAutomobil.getZakladni_vybava()) {
                if (doplnek.getPopis_doplnku().equals(doplnek2.getPopis_doplnku())) {
                    automobil.getTsVybava().select(doplnek.getPopis_doplnku());
                }
            }
        }


        int id;
        try {
            id = automobil.getSwitcher().getMainWindow().getZakaznik().getRole().getId().intValue();
        } catch (NullPointerException e) {
            id = 1;
        }

        AutomobilStateHolder.setState(AutomobilStateHolder.EDIT_AUTOMOBIL_STATE, id, super.automobil);

    }
}
